import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/custom_alert_dialog.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/utils/user_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

class SettingMainPage extends StatefulWidget {
  const SettingMainPage({super.key});

  @override
  State<SettingMainPage> createState() => _SettingMainPageState();
}

class _SettingMainPageState extends State<SettingMainPage> {
  String? cacheLength = "0KB";
  // 是否展示顶部提示文案
  bool show = false;
  String? topDesc = "";

  @override
  void initState() {
    super.initState();
    _getSettingTopTipData();
    getCacheSize();
  }

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  Widget contentView() {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: Colors.white,
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.only(left: 0.w, right: 0.w),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              if (show)
                Container(
                    // height: 80.w,
                    padding: EdgeInsets.only(left: 15.w, top: 14.5.w, bottom: 14.5.w),
                    color: ColorRes.colorEDEDFD,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: EdgeInsets.only(top: 3.w),
                          child: ImageLoader.loadAsset('icon_cp_z_alert.webp', 15.w),
                        ),
                        SizedBox(width: 5.w),
                        Expanded(
                          child: Text(
                            "$topDesc",
                            style: TextStyle(color: ColorRes.color333333, fontSize: 15.sp),
                          ),
                        ),
                      ],
                    )),
              // buildLine(),
              buildItemView("修改登录密码", '', (s) async {
                var info = App.instance.userInfo;
                if (!UserUtils.isAuth(info)) {
                  UserUtils.showAuthDialog(context, info);
                  return;
                }
                context.push(PageUrl.modifyPass);
              }),
              buildLine(),
              buildItemView("更换手机号", '', (s) async {
                var info = App.instance.userInfo;
                if (!UserUtils.isAuth(info)) {
                  UserUtils.showAuthDialog(context, info);
                  return;
                }
                context.push(PageUrl.modifyPhoneNum);
              }),
              buildLine(),
              buildItemView("银行卡管理", '', (s) async {
                var info = App.instance.userInfo;
                if ('3' == info?.status) {
                  UserUtils.showAuthDialog(context, info);
                  return;
                }
                context.push('${PageUrl.bankCardManage}');
              }),
              buildLine(),
              buildItemView("意见反馈", '', (s) async {
                context.push(PageUrl.feedBack);
              }),
              buildLine(),
              buildItemView("清除缓存", cacheLength ?? "0KB", (s) async {
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return const CustomAlertDialog(
                        title: "温馨提示",
                        description: "确定要清空缓存?",
                      );
                    }).then((value) async {
                  if (value == 'onConfirm') {
                    await NativeInterface().confirmClearCache();
                    Future.delayed(const Duration(seconds: 1), () => getCacheSize());
                  }
                });
              }),
              buildLine(),
              buildItemView("注销账号", '', (s) async {
                context.push(PageUrl.cancelAccount);
              }),
            ],
          ),
        ),
      ),
      bottomNavigationBar: Container(
        child: Padding(
          padding: EdgeInsets.fromLTRB(15.w, 0.w, 15.w, 30.w),
          child: ElevatedButton(
            onPressed: () {
              Log.d('退出登录');
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return const CustomAlertDialog(title: "温馨提示", description: "是否退出应用并清除账号信息？");
                  }).then((value) async {
                if (value == 'onConfirm') {
                  await NativeInterface().confirmLogOut();
                }
              });
            },
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6.0),
              ),
              backgroundColor: ColorRes.colorMain,
              elevation: 0, // 移除点击时的阴影效果
              splashFactory: NoSplash.splashFactory, // 禁用水波纹效果
            ),
            child: const Text(
              '退出登录',
              style: TextStyle(fontWeight: FontWeight.w500, color: Colors.white, fontSize: 15),
            ),
          ),
        ),
      ),
    );
  }

  GestureDetector buildItemView(String titleStr, String desc, Function(String title) onTop) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => onTop.call(titleStr),
        child: Container(
            height: 52.w,
            padding: EdgeInsets.only(left: 15.w, right: 15.w),
            child: Row(children: [
              Expanded(
                  child: Text(
                titleStr,
                textAlign: TextAlign.left,
                style: TextStyle(fontSize: 15.sp, color: const Color(0xFF333333), fontWeight: FontWeight.w500),
              )),
              Expanded(
                child: Container(
                  padding: EdgeInsets.only(right: 5),
                  child: Text(
                    "${desc}",
                    textAlign: TextAlign.right,
                    style: TextStyle(fontSize: 14.sp, color: const Color(0xFF666666)),
                  ),
                ),
              ),
              Image.asset("assets/images/grey_setup.webp", width: 6.w, height: 12.w),
              // ImageLoader.loadAsset("icon_right_arrow.webp", 19.w),
            ])));
  }

  Widget buildLine() {
    return Container(
      width: double.infinity,
      height: 0.5,
      color: const Color(0xFFC7C6CC),
    );
  }

  getCacheSize() {
    NativeInterface().getAppOtherInfo().then((AppOtherInfo value) {
      cacheLength = value.cacheLength;
      setState(() {});
    });
  }

  /// 设置密码
  _getSettingTopTipData() async {
    var id = App.instance.userInfo?.id;
    if (id == null || id.isEmpty == true) return;
    var httpRequest = HttpRequest(Api.settingPageTopTips, urlParams: {
      "userMedicalId": id,
    });
    var httpResponse = await HttpClient.get(httpRequest);
    var serviceResult = ServiceResult<dynamic?>.simple(httpResponse);
    print("设置页面顶部提示 = ${httpResponse.body}");
    ToastUtils.showToast(context, serviceResult.responseMsg);
    if (serviceResult.success) {
      show = serviceResult.responseBody?["show"];
      if (show) {
        topDesc = serviceResult.responseBody?["notice"];
      }
      setState(() {});
    }
  }
}
